<template>
  <div class="app-container">
    <el-row :gutter="5">
      <el-col :span="19">
        <el-row :gutter="15" class="mb5">
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:company:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleAgent"
              v-hasPermi="['system:company:edit']"
              >授权</el-button
            >
          </el-col>
          <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
            class="el-form-search"
          >
            <el-form-item
              label="企业名称"
              prop="name"
              class="el-form-search-item"
            >
              <el-input
                v-model="queryParams.name"
                placeholder="请输入企业名称"
                clearable
                size="mini"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item
              label="联系人"
              prop="linkMan"
              class="el-form-search-item"
            >
              <el-input
                v-model="queryParams.linkMan"
                placeholder="请输入联系人"
                clearable
                size="mini"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item
              label="联系电话"
              prop="linkPhone"
              class="el-form-search-item"
            >
              <el-input
                v-model="queryParams.linkPhone"
                placeholder="请输入联系电话"
                clearable
                size="mini"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item class="el-form-search-item">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </el-row>

        <el-table
          ref="list"
          :height="tableHeight"
          v-loading="loading"
          :data="companyList"
          highlight-current-row
          @current-change="handleCurrentChange"
          @row-click="handleRowClick"
      border
        >
          <el-table-column label="#" type="index" width="50" align="center">
            <template scope="scope">
              <span>{{
                (queryParams.pageNum - 1) * queryParams.pageSize +
                scope.$index +
                1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="企业名称"
            header-align="center"
            align="left"
            prop="name"
            min-width="160"
            show-overflow-tooltip
          />
          <el-table-column
            label="联系人"
            header-align="center"
            align="left"
            prop="linkMan"
            width="80"
            show-overflow-tooltip
          />
          <!-- <el-table-column
            label="联系电话"
            align="center"
            prop="linkPhone"
            width="100"
            show-overflow-tooltip
          /> -->
          <!-- <el-table-column
            label="管理员账号"
            align="center"
            prop="userName"
            width="120"
          /> -->
          <el-table-column
            label="最后业务日期"
            align="center"
            prop="lastOptDate"
            width="100"
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.lastOptDate
                  ? parseTime(scope.row.lastOptDate, "{y}-{m}-{d}")
                  : "/"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="最后登录时间"
            align="center"
            prop="lastLoginTime"
            width="140"
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.lastLoginTime
                  ? parseTime(
                      scope.row.lastLoginTime,
                      "{y}-{m}-{d} {h}:{i}:{s}"
                    )
                  : "/"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="授权截止日期"
            align="center"
            prop="effectiveEndDate"
            width="100"
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.effectiveEndDate
                  ? parseTime(scope.row.effectiveEndDate, "{y}-{m}-{d}")
                  : "/"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="企业状态"
            align="center"
            prop="status"
            width="80"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_normal_disable"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            align="center"
            prop="remark"
            width="80"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="190"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click.stop="handleUpdate(scope.row)"
                v-hasPermi="['system:company:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click.stop="handleDelete(scope.row)"
                v-hasPermi="['system:company:remove']"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-circle-check"
                @click="handleCurrentChange(scope.row)"
                v-hasPermi="['system:company:edit']"
                >菜单设置</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改企业管理对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="800px"
          append-to-body
          :close-on-click-modal="false"
          v-dialogDrag
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入企业名称" />
            </el-form-item>
            <el-form-item label="企业简称" prop="alias">
              <el-input v-model="form.alias" placeholder="请输入企业简称" />
            </el-form-item>
            <el-form-item label="联系人" prop="linkMan">
              <el-input v-model="form.linkMan" placeholder="请输入联系人" />
            </el-form-item>
            <el-form-item label="联系电话" prop="linkPhone">
              <el-input
                v-model="form.linkPhone"
                placeholder="请输入联系电话"
                maxlength="11"
              />
            </el-form-item>
            <el-form-item label="管理员账号" prop="userName">
              <el-input
                v-model="form.userName"
                placeholder="请输入管理员账号"
                :disabled="this.form.id"
              />
            </el-form-item>
            <el-form-item label="登录密码" prop="password">
              <el-input
                v-model="form.password"
                placeholder="请输入登录密码"
                :disabled="this.form.id"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 授权对话框 -->
        <el-dialog
          title="企业授权"
          :visible.sync="agentOpen"
          width="800px"
          append-to-body
          :close-on-click-modal="false"
          v-dialogDrag
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="form.name" disabled />
            </el-form-item>
            <el-form-item label="企业状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="授权截止日期" prop="effectiveEndDate">
              <el-date-picker
                v-model="form.effectiveEndDate"
                value-format="yyyy-MM-dd"
                clearable
                type="date"
                placeholder="请选择截止日期"
                style="width: 180px"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="授权用户数" prop="effectiveUserNum">
              <el-input-number
                v-model="form.effectiveUserNum"
                placeholder="请输入授权用户数"
                controls-position="right"
                :min="1"
                style="width: 180px"
              />
            </el-form-item>
            <!-- <el-form-item label="公众号" prop="appId">
              <el-input v-model="form.appId" placeholder="请输入AppId" />
            </el-form-item> -->
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitAgent">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
      <el-col :span="5">
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <div style="display: flex">
              <span class="card-name">{{ companyName }}</span>
              <el-button class="card-btn" type="text" @click="submitMenu">
                <svg-icon icon-class="button" />保存
              </el-button>
            </div>
          </div>
          <div class="card-content">
            <div v-if="companyId" class="menu">
              <el-checkbox
                v-model="menuNodeAll"
                @change="handleCheckedTreeNodeAll($event, 'menu')"
                >全选/全不选</el-checkbox
              >
              <el-scrollbar style="height: 100%; width: 100%">
                <el-tree
                  :data="menuOptions"
                  show-checkbox
                  ref="menu"
                  node-key="id"
                  empty-text="加载中，请稍候"
                  :props="defaultProps"
                  default-expand-all
                ></el-tree
              ></el-scrollbar>
            </div>
            <div v-else class="empty">
              <el-empty description="请选择企业" :image-size="80"></el-empty>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  listCompany,
  getCompany,
  delCompany,
  addCompany,
  updateCompany,
  agentCompany,
} from "@/api/system/company";
import {
  effectTreeSelect as menuTreeselect,
  companyMenuTreeselect,
  updateCompanyMenu,
} from "@/api/system/menu";

export default {
  name: "Company",
  dicts: ["sys_normal_disable", "sys_industry"],
  data() {
    return {
      // 默认密码
      initPassword: undefined,
      menuNodeAll: false,
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      companyId: null,
      companyName: "企业菜单",
      // 表格高度
      tableHeight: "calc(100vh - 200px)",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业管理表格数据
      companyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      agentOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        orderByColumn: "id",
        isAsc: "asc",
        name: null,
        linkMan: null,
        linkPhone: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "企业名称不能为空", trigger: "blur" },
        ],
        linkMan: [
          { required: true, message: "联系人不能为空", trigger: "blur" },
        ],
        linkPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        userName: [
          { required: true, message: "管理员账号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "登录密码不能为空", trigger: "blur" },
        ],
        effectiveYear: [
          { required: true, message: "授权年数不能为空", trigger: "blur" },
        ],
        effectiveUserNum: [
          { required: true, message: "授权用户数不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询企业管理列表 */
    getList() {
      this.loading = true;
      listCompany(this.queryParams).then((response) => {
        this.companyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.agentOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        industry: null,
        province: null,
        city: null,
        area: null,
        address: null,
        linkMan: null,
        linkPhone: null,
        effectiveYear: null,
        effectiveStartDate: null,
        effectiveEndDate: null,
        effectiveUserNum: null,
        userName: null,
        password: null,
        logo: null,
        agentUnit: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业";
      this.form.password = this.initPassword;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCompany(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改企业";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCompany(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCompany(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除记录？")
        .then(function () {
          return delCompany(ids);
        })
        .then(() => {
          this.companyId = null;
          this.companyName = "企业菜单";
          this.menuNodeAll = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 菜单设置
    handleCurrentChange(row) {
      if (row) {
        this.menuNodeAll = false;
        this.companyName = "加载中...";
        this.getMenuTreeselect(row);
      }
    },
    submitMenu() {
      const menuIds = this.getMenuAllCheckedKeys();
      // 保存企业菜单
      updateCompanyMenu(this.companyId, menuIds).then((response) => {
        this.$modal.msgSuccess("保存成功");
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect(row) {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
        this.companyId = row.id;
        this.companyName = row.name;
        const companyMenu = this.getCompanyMenuTreeselect(this.companyId);
        companyMenu.then((res) => {
          let checkedKeys = res.checkedKeys;
          checkedKeys.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.menu.setChecked(v, true, false);
            });
          });
        });
      });
    },
    /** 根据企业ID查询菜单树结构 */
    getCompanyMenuTreeselect(companyId) {
      return companyMenuTreeselect(companyId).then((response) => {
        // this.menuOptions = response.menus;
        return response;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
    },
    handleRowClick(row, column, event) {
      this.ids = row.id;
    },
    /** 授权 */
    handleAgent() {
      this.reset();
      const id = this.ids;
      if (id.length < 1) {
        return this.$modal.msgWarning("请选择企业");
      }
      getCompany(id).then((response) => {
        this.form = response.data;
        this.agentOpen = true;
      });
    },
    /** 授权提交按钮 */
    submitAgent() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          agentCompany(this.form).then((response) => {
            this.$modal.msgSuccess("授权成功");
            this.agentOpen = false;
            this.getList();
          });
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.card-btn {
  float: right;
  padding: 3px 0;
  font-size: 16px;
}

.card-name {
  font-size: 16px;
  color: #666;
  width: 200px;
  max-width: 200px;
  display: inline-block;
  white-space: nowrap; /*设置文字禁止换行*/
  overflow: hidden; /* 内容超出宽度时隐藏超出部分的内容 */
  text-overflow: ellipsis; /* 当对象内文本溢出时显示省略标记(...) ；需与overflow:hidden;一起使用。*/
}

.card-content {
  min-height: calc(100vh - 155px);
  .menu {
    height: calc(100vh - 155px);
    max-height: calc(100vh - 155px);
  }
  .empty {
    padding-top: 100px;
  }
}

::v-deep .el-card__body {
  padding: 5px 0px 0 10px;
}

::v-deep .el-scrollbar__wrap {
  margin-top: 5px;
  border-top: 1px solid #eee;
  overflow-x: hidden;
  padding-bottom: 30px;
}
</style>
